import random
import json
import re
import os
import pyperclip
import tkinter as tk
import pyautogui
import tkinter as tk
from tkinter.simpledialog import askstring
from docx import Document
import time
import shift_rec
from multiprocessing.dummy import Pool
import random

# class MyThread(threading.Thread):
#     def __init__(self, func, *args):
#         super().__init__()
#         self.func = func
#         self.args = args
#         self.setDaemon(True)
#         self.start()

#     def run(self):
#         self.func(*self,args)


#     """
#     command = lambda :MyThread(func, args)
#     """
def do_string(matched):

    if matched.group(2):
        year_value = int(matched.group(2))
    else:
        year_value = 0
    if matched.group(4):
        month_value = int(matched.group(4)) / 12

    else:
        month_value = 0

    return str(year_value + month_value) if year_value + month_value else ''


def form_TPRBP(age, copy_flag=True):
    age = re.sub(r'\d+天', '', age)
    if not re.search(r'((\d*)岁)?((\d*)月)?', age).group():
        return ''
    else:
        age = float(re.sub(r'((\d*)岁)?((\d*)月)?', do_string, age))

        result = ''
        temp = '36.%s' % random.randint(1, 9)

        with open('.\\myjson\\TPRBP.json', 'r', encoding='utf-8') as f:
            base_data = json.load(f)
        for each_data in base_data:
            if each_data['age'][0] < age <= each_data['age'][1]:
                pulse = random.randrange(*each_data['pulse'])
                respire = random.randrange(*each_data['respire'])
                sbp = random.randrange(*each_data['sbp'])
                dbp = int(sbp * 2 / 3)
                result = 'T：%s℃  P：%s次/分 R：%s次/分 BP：%s/%smmHg W：' % (
                    temp, pulse, respire, sbp, dbp)
                break
        if copy_flag:
            pyperclip.copy(result)
        return result


# class FormPHI(tk.Toplevel):
class FormPHI(tk.Tk):
    def __init__(self, ):
        super().__init__()
        self.title('现病史')
        sw = self.winfo_screenwidth()
        sh = self.winfo_screenheight()
        ww = 650
        wh = 700
        self.geometry("%dx%d+%d+%d" % (ww, wh, (sw - ww) / 2, (sh - wh) / 2))
        self.after(1, lambda: self.focus_force())

        # 生成现病史
        with open('.\\myjson\\symptom.json', 'r', encoding='utf-8') as f:
            symptom = json.load(f)
        positive_sym = symptom['阳性症状']
        negative_sym = symptom['阴性症状']
        self.symptom = symptom

        # 阳性症状
        tk.Label(self, text="阳性症状：").grid(row=0)
        self.var_positive = {}
        row_idx = 1
        col_idx = 0
        for k in positive_sym.keys():
            self.var_positive[k] = tk.BooleanVar()
            tk.Checkbutton(self, text=k,
                           variable=self.var_positive[k]).grid(row=row_idx,
                                                               column=col_idx,
                                                               sticky="w")
            col_idx += 1
            if col_idx > 3:
                row_idx += 1
                col_idx = 0
        # 阴性症状
        tk.Label(self, text="阴性症状：").grid(row=row_idx + 1)
        self.var_negative = {}
        row_idx_neg = row_idx + 2
        col_idx_neg = 0
        for k_neg in negative_sym:
            self.var_negative[k_neg] = tk.BooleanVar()
            tk.Checkbutton(self, text=k_neg,
                           variable=self.var_negative[k_neg]).grid(
                               row=row_idx_neg, column=col_idx_neg, sticky="w")
            col_idx_neg += 1
            if col_idx_neg > 3:
                row_idx_neg += 1
                col_idx_neg = 0

        btn_frame = tk.Frame(self)
        btn_frame.grid(row=row_idx_neg + 1, columnspan=5)
        tk.Button(btn_frame,
                  text='现病史',
                  command=self.confirm,
                  width=12,
                  height=1,
                  activebackground='grey',
                  relief='groove').grid(row=row_idx_neg + 1,
                                        column=0,
                                        columnspan=2,
                                        padx=10)
        tk.Button(btn_frame,
                  text='症状',
                  command=self.symptom_add,
                  width=12,
                  height=1,
                  activebackground='grey',
                  relief='groove').grid(row=row_idx_neg + 1,
                                        column=3,
                                        columnspan=2,
                                        padx=10)
        tk.Button(btn_frame,
                  text='退出',
                  command=self.cancel,
                  width=12,
                  height=1,
                  activebackground='grey',
                  relief='groove').grid(row=row_idx_neg + 1,
                                        column=5,
                                        columnspan=2,
                                        padx=10)

    def confirm(self):
        select = '天前，患儿无诱因出现'
        treatment = '就诊于当地医院，给予口服药物应用（具体用药用法用量不详），效差。'
        outpatient_treatment = '今为求进一步治疗来我院，门诊以“”收住我科。发病来，患儿神志清，精神食欲欠佳，睡眠一般，大、小便基本正常。近期患儿体重无明显变化。'
        positive_sym = {}
        negative_sym = []

        for k, v in self.var_positive.items():
            if v.get():
                positive_sym[k] = self.symptom['阳性症状'][k]
            else:
                negative_sym.append(k)
        for k_neg, v_neg in self.var_negative.items():
            if v_neg.get():
                negative_sym.append(k_neg)

        positive_sym_clause = ""
        for k_pos, v_pos in positive_sym.items():
            positive_sym_clause += "伴%s，%s" % (k_pos, v_pos)
        negative_sym_clause = ""
        for each in negative_sym:
            negative_sym_clause += "无%s，" % (each)
        select += positive_sym_clause.lstrip(
            "伴") + negative_sym_clause + treatment + outpatient_treatment

        pyperclip.copy(select)

    def symptom_add(self):
        select = ''
        positive_sym = {}
        negative_sym = []

        for k, v in self.var_positive.items():
            if v.get():
                positive_sym[k] = self.symptom['阳性症状'][k]
            else:
                negative_sym.append(k)
        for k_neg, v_neg in self.var_negative.items():
            if v_neg.get():
                negative_sym.append(k_neg)

        positive_sym_clause = ""
        for k_pos, v_pos in positive_sym.items():
            positive_sym_clause += "伴%s，%s" % (k_pos, v_pos)
        negative_sym_clause = ""
        for each in negative_sym:
            negative_sym_clause += "无%s，" % (each)
        select += positive_sym_clause + negative_sym_clause

        pyperclip.copy(select)

    def cancel(self):
        self.destroy()


def fill_p_info():

    fill_info = askstring(
        '请输入',
        '现住址，身份证号，联系人姓名，电话空格分开：',
    )
    pyperclip.copy(fill_info)
    addr, id_no, contact_person, phone = fill_info.split()
    info_map = {
        "ward": "儿童消化心血管科",
        "province": "河南省",
        "city": "南阳市",
        "work": "其他",
        "marriage": "未婚",
        "nation": "汉族",
        "null": "无",
        "condition": "一般",
        "ralationship": "父母",
        "teller": "患者家属",
        "contact_person": contact_person,
        "addr": addr,
        "id_no": id_no,
        "phone": phone,
        "c": "c",
        "v1": "v1",
        "v2": "v2",
        "blank": ''
    }

    info_list = [
        'ward', 'blank', 'province', 'city', 'work', 'marriage', 'nation',
        'province', 'city', 'null', 'null', 'addr', 'id_no', 'contact_person',
        'condition', 'ralationship', 'c', 'phone', 'v1', 'addr', 'teller',
        'null', 'v2'
    ]
    pyautogui.click(1749, 200)
    for i in info_list:
        if i == 'c':
            pyautogui.hotkey('ctrl', 'a')
            pyautogui.hotkey('ctrl', 'c')
            date1 = pyperclip.paste()
            date_, time_ = date1.split()
            h, m = time_.split(':')
            date2 = f"{date_} {int(h)+1}:{int(m)+1 if int(m)+1>=59 else 15}"
            date3 = f"{date_} {int(h)+1}:{int(m)+1 if int(m)+20>=59 else 20}"

        elif i == 'v1':
            pyperclip.copy(date2)
            pyautogui.hotkey('ctrl', 'v')

        elif i == 'v2':
            pyperclip.copy(date3)
            pyautogui.hotkey('ctrl', 'v')
        elif not info_map[i]:
            pass
        else:
            pyperclip.copy(info_map[i])
            pyautogui.hotkey('ctrl', 'v')
        pyautogui.press('tab')


def fake_xghs(text_info: dict):
    """
    生成新冠核酸报告
    text_info: dict
    {
        "日期": "2021-11-30",
        "随机码": "20211130PCR6589",
        "姓名": "",
        "性别": "",
        "年龄": "",
        "门诊号": "700101356",
        "开单时间": "2021-12-02 10:39",
        "报告时间": "2021-12-02 13:21",
        
    }
    
    """
    d = Document(f'.\\mydocx\\核酸{random.randint(1,2)}.docx')

    # 获取word文档内的表格列表
    t = d.tables
    # 第一个表格为病人基本信息，包括姓名、性别、年龄
    t1 = t[0]
    t2 = t[1]
    info_to_fill_t1 = {
        (0, 0): text_info["日期"],
        (1, 6): text_info["随机码"],
        (2, 1): text_info['姓名'],
        (2, 2): text_info['性别'],
        (2, 4): text_info['年龄'],
        (3, 1): text_info['门诊号'],
    }
    info_to_fill_t2 = {
        (0, 1): text_info["开单时间"],
        (0, 2): text_info["报告时间"],
    }
    for k1, v1 in info_to_fill_t1.items():

        if (k1[0], k1[1]) == (0, 0):
            run1 = t1.cell(k1[0], k1[1]).paragraphs[0].add_run(v1)
            run1.font.name = '楷体'
            run1.font.size = 130000
        else:
            run = t1.cell(k1[0], k1[1]).paragraphs[0].add_run(v1)
            run.font.name = '宋体'
            run.font.size = 140000
    for k2, v2 in info_to_fill_t2.items():
        run = t2.cell(k2[0], k2[1]).paragraphs[0].add_run(v2)
        run.font.name = '宋体'
        run.font.size = 130000

    save_name = "%s_%s_%s" % (time.strftime(
        "%Y%m%d", time.localtime()), text_info["姓名"], text_info["日期"])
    
    if not os.path.exists('E:\\核酸'):
        os.mkdir('E:\\核酸')
    d.save('E:\\核酸\\%s.docx' % save_name)
    os.startfile('E:\\核酸\\%s.docx' % save_name)
    #shift_rec.print_file(os.path.abspath('E:\\核酸\\%s.docx' % save_name))


class XghsUI(tk.Tk):
    def __init__(self, ):
        super().__init__()
        self.title('输入信息(8100)')
        sw = self.winfo_screenwidth()
        sh = self.winfo_screenheight()
        ww = 400
        wh = 400
        self.geometry("%dx%d+%d+%d" % (ww, wh, (sw - ww) / 2, (sh - wh) / 2))
        self.after(1, lambda: self.focus_force())
        self.result = {}
        self.pid = tk.StringVar()
        self.date_ = tk.StringVar()
        self.date_.set(time.strftime('%Y.%m.%d', time.localtime()))
        self.name = tk.StringVar()
        self.name.set('请输入姓名：')
        self.sex = tk.StringVar()
        self.sex.set('男')
        self.age = tk.StringVar()
        self.age.set('请输入年龄：')

        self.start = tk.StringVar()
        self.start.set('7')
        self.stop = tk.StringVar()
        self.stop.set('16')
        self.infor_frame = tk.Frame(self)
        self.infor_frame.pack(pady=5)
        tk.Label(self.infor_frame, text="住院号：").pack(side=tk.LEFT)
        tk.Entry(self.infor_frame, textvariable=self.pid).pack(side=tk.LEFT)
        self.pid_btn = tk.Button(self.infor_frame,
                                 text='查询',
                                 command=self.query_info)
        self.pid_btn.pack(side=tk.LEFT)
        set_time = tk.Frame(self)
        set_time.pack()
        tk.Label(set_time, text="开单时间范围 从").pack(pady=5, side=tk.LEFT)
        tk.Entry(set_time, textvariable=self.start, width=2).pack(pady=5, side=tk.LEFT)
        tk.Label(set_time, text="点到").pack(pady=5, side=tk.LEFT)
        tk.Entry(set_time, textvariable=self.stop, width=2).pack(pady=5, side=tk.LEFT)
        tk.Label(set_time, text="点").pack(pady=5, side=tk.LEFT)
        tk.Label(
            self,
            text=f"日期【格式：{time.strftime('%Y.%m.%d', time.localtime())}】").pack(
                pady=5)
        tk.Entry(self, textvariable=self.date_).pack(pady=5)
        tk.Label(self, text="姓名").pack(pady=5)
        tk.Entry(self, textvariable=self.name).pack(pady=5)
        tk.Label(self, text="性别").pack(pady=5)

        sex_frame = tk.Frame(self)
        sex_frame.pack()
        for v_ in ['男', '女', '未知']:
            tk.Radiobutton(
                sex_frame,
                variable=self.sex,
                text=v_,
                value=v_,
            ).pack(padx=10, side=tk.LEFT)
        tk.Label(self, text="年龄").pack(pady=5)
        tk.Entry(self, textvariable=self.age).pack(pady=5)
        self.bind_class("Entry", '<ButtonRelease-1>', self.select_all)
        self.bind_all('<Return>', self.query_info)
        btn_frame = tk.Frame(self)
        btn_frame.pack(side=tk.BOTTOM, pady=10)
        tk.Button(btn_frame,
                  text='打印',
                  command=self.confirm,
                  width=12,
                  height=1,
                  activebackground='grey',
                  relief='groove').pack(side=tk.LEFT, padx=10)
        tk.Button(btn_frame,
                  text='取消',
                  command=self.cancel,
                  width=12,
                  height=1,
                  activebackground='grey',
                  relief='groove').pack(side=tk.LEFT)

    def query_info(self, event=''):
        new_patient_id = self.pid.get()
        query_app = shift_rec.AcquireInfoTotal(new_patient_id)
        query_list = [
            '病程记录',
        ]
        pool = Pool(2)
        query_result = pool.map(query_app.query_content, query_list)
        query_dic = {}
        for each_result in query_result:
            query_dic.update(each_result)
        data_resolved = shift_rec.DataResolver(query_app.pid)
        data_resolved.record_resolve(query_dic)

        if data_resolved.patient_info:
            patient_info = data_resolved.patient_info
        self.date_.set(patient_info.setdefault('入院时间', '').split()[0])
        self.name.set(patient_info.setdefault('姓名', ''))
        self.sex.set(patient_info.setdefault('性别', ''))
        self.age.set(patient_info.setdefault('年龄', ''))
        self.update()

    def confirm(self):
        start_ = int(self.start.get() if self.start.get() else 7)
        stop_ = int(self.stop.get() if self.stop.get() else 16)
        date_get = '-'.join(self.date_.get().split('.'))
        code = random.randint(1112, 8756)
        num = random.randint(700101356, 700901356)
        m_rdm = random.randint(start_, stop_)
        s_rdm = random.randint(10, 44)
        time_str_start = f"{str(m_rdm).rjust(2,'0')}:{s_rdm}"
        time_str_end = f"{str(m_rdm+2).rjust(2,'0')}:{s_rdm+11}"

        self.result = {
            "日期": date_get,
            "随机码": f"{''.join(date_get.split('-'))}PCR{code}",
            "姓名": self.name.get(),
            "性别": self.sex.get(),
            "年龄": self.age.get(),
            "门诊号": str(num),
            "开单时间": f"{date_get} {time_str_start}",
            "报告时间": f"{date_get} {time_str_end}",
        }

        fake_xghs(self.result)

    def cancel(self):
        self.destroy()

    def select_all(self, event):
        # event.widget 即触发事件的控件，可以直接用它的方法如.select_range()等
        event.widget.select_range(0, tk.END)


if __name__ == "__main__":
    if not os.path.exists('E:\\核酸'):
        os.mkdir('E:\\核酸')
    app = XghsUI()
    app.mainloop()
